﻿using System;
using System.Globalization;
using System.IO.Compression;
using System.Web;

namespace Nasa8x.Web.UI.Http.Modules
{
    public class ResourceCompression : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += Compress; 
        }

        public void Compress(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            HttpRequest request = app.Request;
            HttpResponse response = app.Response;

            //Ajax Web Service request is always starts with application/json
            if (request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json"))
            {
                //Skip Compression for IE6, User may be using an older version of IE6 which does not support compression
                if (!((request.Browser.IsBrowser("IE")) && (request.Browser.MajorVersion <= 6)))
                {
                    string acceptEncoding = request.Headers["Accept-Encoding"];

                    if (!string.IsNullOrEmpty(acceptEncoding))
                    {
                        acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);

                        if (acceptEncoding.Contains("gzip"))
                        {
                            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                            response.AddHeader("Content-encoding", "gzip");
                        }
                        else if (acceptEncoding.Contains("deflate"))
                        {
                            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                            response.AddHeader("Content-encoding", "deflate");
                        }
                    }
                }
            }

        }

        public void Dispose()
        {
           
        }
    }
}
